import tkinter as tk
from tkinter import ttk
import json
from datetime import datetime

class ResultsDisplay(ttk.Frame):
    def __init__(self, parent):
        super().__init__(parent)
        self.create_widgets()
        self.processed_iterations = set()

    def create_widgets(self):
        # Notebook
        self.notebook = ttk.Notebook(self)
        self.notebook.pack(fill=tk.BOTH, expand=True)

        # Process output
        self.process_output = tk.Text(self.notebook, height=10, state=tk.DISABLED, 
                                    foreground='white', background='#404040')
        self.notebook.add(self.process_output, text="计算过程输出")

        # Result output with horizontal scroll
        result_frame = ttk.Frame(self.notebook)
        
        # Create canvas and scrollbar
        canvas = tk.Canvas(result_frame)
        h_scroll = ttk.Scrollbar(result_frame, orient=tk.HORIZONTAL, command=canvas.xview)
        v_scroll = ttk.Scrollbar(result_frame, orient=tk.VERTICAL, command=canvas.yview)
        
        # Create scrollable frame
        scrollable_frame = ttk.Frame(canvas)
        scrollable_frame.bind(
            "<Configure>",
            lambda e: canvas.configure(
                scrollregion=canvas.bbox("all")
            )
        )
        
        canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
        canvas.configure(xscrollcommand=h_scroll.set, yscrollcommand=v_scroll.set)
        
        # Layout scrollable area
        canvas.grid(row=0, column=0, sticky="nsew")
        v_scroll.grid(row=0, column=1, sticky="ns")
        h_scroll.grid(row=1, column=0, sticky="ew")
        
        # Configure grid weights
        result_frame.grid_rowconfigure(0, weight=1)
        result_frame.grid_columnconfigure(0, weight=1)
        
        # Create result frame inside scrollable frame
        self.result_frame = ttk.Frame(scrollable_frame)
        self.result_frame.grid(row=0, column=0, sticky="nsew")
        
        self.notebook.add(result_frame, text="最终结果")

    def process_final_results(self):
        """处理并显示最终结果"""
        # Clear existing items
        for widget in self.result_frame.winfo_children():
            widget.destroy()
            
        # 读取results_final.json文件
        try:
            with open('results/results_final.json') as f:
                data = json.load(f)
                results = data['results']
                
                for result in results:
                    # Create a new frame for each result
                    result_frame = tk.Frame(self.result_frame)
                    result_frame.pack(fill=tk.X, pady=5)
                    
                    # Display rank, total profit and total time
                    tk.Label(result_frame, text=f"排名: {result['rank']}", 
                           font=('微软雅黑', 10)).grid(row=0, column=0, sticky=tk.W, columnspan=2)
                    
                    # 直接显示总用时，保留1位小数
                    total_time = float(result['total_time'])
                    time_str = f"{total_time:.1f}"
                    
                    # Display total profit and time
                    tk.Label(result_frame, 
                           text=f"总积分: {result['total_profit']}  总时间: {time_str} 分钟",
                           font=('微软雅黑', 10)).grid(row=1, column=0, sticky=tk.W, columnspan=2)
                    
                    # Create grid layout for path and details
                    tk.Label(result_frame, text="路径", font=('微软雅黑', 10)).grid(row=2, column=0, sticky=tk.W)
                    path_frame = tk.Frame(result_frame)
                    path_frame.grid(row=2, column=1, sticky=tk.W)

                    tk.Label(result_frame, text="积分", font=('微软雅黑', 10)).grid(row=3, column=0, sticky=tk.W)
                    profits_frame = tk.Frame(result_frame)
                    profits_frame.grid(row=3, column=1, sticky=tk.W)

                    tk.Label(result_frame, text="用时", font=('微软雅黑', 10)).grid(row=4, column=0, sticky=tk.W)
                    times_frame = tk.Frame(result_frame)
                    times_frame.grid(row=4, column=1, sticky=tk.W)

                    # Set fixed column width for alignment
                    column_width = 30
                    for i in range(len(result['path'])*2):
                        path_frame.grid_columnconfigure(i, minsize=column_width)
                        profits_frame.grid_columnconfigure(i, minsize=column_width)
                        times_frame.grid_columnconfigure(i, minsize=column_width)
                    
                    # Display path with arrows and align profits and times
                    path_points = result['path']
                    profits = result['point_profits']
                    times = result['path_times']
                    
                    # Path row
                    for i, point in enumerate(path_points):
                        tk.Label(path_frame, text=point, font=('微软雅黑', 10)).grid(row=0, column=i*2)
                        if i < len(path_points) - 1:
                            tk.Label(path_frame, text=' → ', font=('微软雅黑', 10)).grid(row=0, column=i*2+1)
                    
                    # Profits row
                    for i, profit in enumerate(profits):
                        tk.Label(profits_frame, text=str(profit).rjust(2), 
                               font=('微软雅黑', 10)).grid(row=0, column=i*2)
                        if i < len(profits) - 1:
                            tk.Label(profits_frame, text=' ' * 3, 
                                   font=('微软雅黑', 10)).grid(row=0, column=i*2+1)
                    
                    # Times row
                    for i, time in enumerate(times):
                        if i == 0:
                            tk.Label(times_frame, text=' ' * 3, 
                                   font=('微软雅黑', 10)).grid(row=0, column=0)
                        tk.Label(times_frame, text=f"{time:.1f}".rjust(3),
                               font=('微软雅黑', 10)).grid(row=0, column=i*2+1)
                        if i < len(times) - 1:
                            tk.Label(times_frame, text=' ' * 3, 
                                   font=('微软雅黑', 10)).grid(row=0, column=i*2+2)
                    
                    # Add separator
                    separator = ttk.Separator(result_frame, orient=tk.HORIZONTAL)
                    separator.grid(row=5, column=0, columnspan=max(len(path_points)*2, 1), sticky=tk.EW, pady=5)
                    
        except Exception as e:
            tk.Label(self.result_frame, text=f"读取结果文件失败: {str(e)}",
                   font=('微软雅黑', 10), fg='red').grid(row=0, column=0, sticky=tk.W)

    def update_results_display(self, data):
        """更新结果显示"""
        iteration = data.get('iteration', 'final')
        results = data['results']
        timestamp = data['timestamp']
        
        # 将时间戳转换为HH:MM格式
        dt = datetime.fromisoformat(timestamp)
        time_str = dt.strftime('%H:%M')
        
        self.process_output.config(state=tk.NORMAL)
        if iteration == 'final':
            return
            
        # 添加None值检查
        if iteration is not None:
            res = results[0]
            # 直接显示总用时，保留1位小数
            total_time_str = f"{res['total_time']:.1f}"
            
            path_str = ' → '.join(res['path'])
            
            self.process_output.insert(tk.END, 
                #f"迭代 {iteration} 结果:\n"
                f"当前时间: {time_str}\n"
                f"当前最优积分: {res['total_profit']}\n"
                f"路线: {path_str}\n"
                f"总用时: {total_time_str} 分钟\n\n")
        self.process_output.see(tk.END)
        self.process_output.config(state=tk.DISABLED)

    def append_output(self, text):
        """添加输出到过程输出面板"""
        if "callback" in text.lower():
            return
        self.process_output.config(state=tk.NORMAL)
        self.process_output.insert(tk.END, text + "\n")
        self.process_output.see(tk.END)
        self.process_output.config(state=tk.DISABLED)
